package com.example.database.library;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class UserFunctions {
	
	private JSONParser jsonParser;
	
	private static String LoginURL = "http://10.0.2.2/android_booklib/";
	private static String RegisterURL = "http://10.0.2.2/android_booklib/";
	private static String forgPassURL = "http://10.0.2.2/android_booklib/";
	private static String BookListURL = "http://10.0.2.2/android_booklib/booklist.json";
	
	private static String login_tag = "login";
	private static String register_tag = "register";
	private static String passforg_tag = "passforg";
	private static String booklist_tag = "booklist";
	// constructor
	public UserFunctions(){
		jsonParser = new JSONParser();
	}
	

	public JSONObject loginUser(String email, String password){
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", login_tag));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("password", password));
		JSONObject json = jsonParser.getJSONFromUrl(LoginURL, params);
		// return json
//		 Log.e("JSON", json.toString());
		return json;
	}
	
	public JSONObject registerUser(String name, String email, String password){
		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", register_tag));
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("email", email));
		params.add(new BasicNameValuePair("password", password));
		
		// getting JSON Object
		JSONObject json = jsonParser.getJSONFromUrl(RegisterURL, params);
		// return json
		return json;
	}
	
	public JSONObject forgotPassword(String email) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", passforg_tag));
		params.add(new BasicNameValuePair("email", email));
		
		JSONObject json = jsonParser.getJSONFromUrl(forgPassURL, params);
		return json;
	}
	
	public JSONObject Booklist() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("tag", booklist_tag));
		JSONObject json = jsonParser.getJSONFromUrl(BookListURL, params);
		return json;
	}
	
	public boolean isUserLoggedIn(Context context){
		DatabaseHandler db = new DatabaseHandler(context);
		int count = db.getRowCount();
		if(count > 0){
			// user logged in
			return true;
		}
		return false;
	}
	

	public boolean logoutUser(Context context){
		DatabaseHandler db = new DatabaseHandler(context);
		db.resetTables();
		return true;
	}
	
}
